package client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Scanner;

import common.Server;


public class Client {

	public static void main(String args[]) {


		try {

			Server server = (Server) Naming.lookup("rmi://"+args[0]+"/server");
			System.out.println("Connected to server "+args[0]+" ...\n");

			Scanner sc = new Scanner (System.in);
			String s1 = "";
			//System.out.print("Enter storage server's IPv4 address (to quit enter 'q'): ");

			System.out.print("Choose operation (to quit enter 'q'): Type 'r' (read) or 'w' (write) -->");


			while(sc.hasNext()){
				s1 = sc.next();

				if(s1.equals("q")) {
					System.out.println("Exiting..." );
					return;
				}
					

				if(s1.equals("r")){

					System.out.print("Insert dataId to read: ");
					s1 = sc.next();
					if(s1.equals("q")) {
						System.out.println("Exiting..." );
						return;
					}
					Integer readValue = server.read(Integer.valueOf(s1));
					if(readValue!=null){
						System.out.printf("dataId = %d, value = %d\n" ,Integer.valueOf(s1), readValue);
					} else {
						System.out.println("No entry found with given dataId." );
					}
							
						
					
					System.out.print("\nChoose operation (to quit enter 'q'): Type 'r' (read) or 'w' (write) -->");

				} else if(s1.equals("w")){

					int dataId = 0;
					int newValue = 0;

					System.out.print("Insert dataId to write on: ");
					s1 = sc.next();
					if(s1.equals("q")) {
						System.out.println("Exiting..." );
						return;
					}
					dataId = Integer.valueOf(s1).intValue();

					System.out.print("Insert new value: ");
					s1 = sc.next();
					if(s1.equals("q")) {
						System.out.println("Exiting..." );
						return;
					}
					newValue = Integer.valueOf(s1).intValue();

					server.write(dataId, newValue);

					System.out.println("\nOperation done!");
					System.out.print("\nChoose operation (to quit enter 'q'): Type 'r' (read) or 'w' (write) -->");


				} else {
					System.err.println("Operation not valid.");
					System.out.print("Choose operation (to quit enter 'q'): Type 'r' (read) or 'w' (write) -->");
				}

			}



		} catch (MalformedURLException e) {
			System.err.print("The IPv4 address entered is malformed.");
			//e.printStackTrace();
			return;

		} catch (RemoteException | NotBoundException e) {
			System.err.println("A communication problem to the given IP address occurred. Exiting...");

			//e.printStackTrace();
			return;

		}






		//} catch (Exception e) {
		//	System.err.println("Caught exception:");
		//	e.printStackTrace();
		//}
	}    
}